var fs = require('fs');
var handler = require('../view_handler');

function load(request, response, parameters) {
  var view_id = 'view/file_list.html';
  
  fs.readFile(view_id, 'utf-8', function(err, data) {
    if(err) {
      var error_message = 'Ocorreu um erro ao tentar carregar o recurso ' + view_id + '.<br>Detalhe: ' + err.toString();
      render_error_page(request, response, error_message);
      console.error('ERROR: ' + error_message);
      
      return;
    }

    var files = fs.readdirSync(process.env['HOME'] + '/anexos');
    var titles = ['Arquivo'];
    var data_list = [files.length];
    
    for (i = 0; i < files.length; i++) {
      data_list[i] = new Array('<input type="checkbox" name="chk' + (i + 1) + '" value="' + files[i] + '">' + files[i]);
    }
    
    data = data.replace(/<%[\s]*data_table[\s]*%>/, require('../components/data_table').rendered(titles, data_list));
    render(request, response, data);
  });  
}

function render(request, response, data) {
  handler.render_content(request, response, data);
}

exports.load = load;
